<?php
/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/

jimport ( 'joomla.application.component.model' );
jimport ( 'joomla.filesystem.file' );
JTable::addIncludePath ( JPATH_COMPONENT . DS . 'tables' );

/**
 * @package Joomla
 * @subpackage JobBoard
 */
class JobBoardModelJAApplications extends JModel {
	var $_table;
	var $_pagination;
	var $_fieldList = null;
	var $_searchparams;
	var $_fieldListEdit;
	var $_table_name = 'ja_applications';
	
	/**
	 * Return the query is used to retrive all row from database
	 * @return string The query is used 
	 */
	function getItems($where_more = '', $limit = 20, $limitstart = 0, $order = '') {
		global $mainframe, $jbconfig, $option;
		
		// Get the page/component configuration
		$params = &$mainframe->getParams ();
		
		$db = JFactory::getDBO ();

		$request = JRequest::get('request');
		$filter_field_keys = array();
		if($request){
			$filter_field_keys = array_keys($request);
		}
		
		$search = JRequest::getVar ( 'search', '' );
		$search = trim(JString::strtolower ( $search ));
		
		$user = JFactory::getUser ();
		$this->getFieldList ( ' and fl.admin_only=0 ' );
		$this->getEditFieldList ( ' and f.frontend_hidden=0' );
				
		$filter_order = JRequest::getVar('filter_order', 'a.id');
		$filter_order_Dir	= JRequest::getVar("filter_order_Dir",	"DESC");
		
		// just in case filter_order get's messed up
		$join = '';
		$orderby = '';
		$where = "";
		$fields_show = '';
		
		$join_clause_field = array ();
		$join_clause_table = array ();
		$field_temp = array();
		$subwhere = array ();		
		$where_clause = array();	
				
		JB_Build_where($join_clause_table, $join_clause_field, $field_temp, $where_clause, $this->_fieldListEdit, $filter_field_keys, $request, $search, $subwhere);			
		
		if ($order) {
			$orderby .= $order;
		}
		if ($filter_order) {			
			if ($orderby)	$orderby .= ',';
			$orderby .= $filter_order . ' ' . $filter_order_Dir ;
		
		} elseif (! $order) {
			$orderby = " a.id";
		}
		
		if($field_temp){
			$fields_show = ', '. implode(', ', $field_temp);	
		}
		
		foreach ($join_clause_table as $j=>$table){
			$join .= "\n $table ";
			if(isset($join_clause_field[$j])){
				$join .= $join_clause_field[$j];
			}
		}
			
		if ($where_clause) {
			$where = ' AND ' .implode(' AND ', $where_clause);
		}
		
		/* Count items */
		$query = "SELECT count(distinct a.id) ".
					"\n FROM #__$this->_table_name as a" .				
					$join.
					"\n WHERE 1=1 ".  $where. $where_more;	
		
		$db->setQuery ( $query );//echo $db->getQuery();exit;
		$total = $db->loadResult ();
		
		jimport ( 'joomla.html.pagination' );
		$this->_pagination = new JPagination ( $total, $limitstart, $limit );
		
		/* Get all items */
		$query = "SELECT distinct a.id, a.* $fields_show" . 
					"\n FROM #__$this->_table_name as a" .				
					$join.
					"\n WHERE 1=1 ".  $where. $where_more.
					"\n ORDER BY ". $orderby . ', a.id desc';
		
		$db->setQuery ( $query, $limitstart, $limit );//echo $db->getQuery();exit;
		
		$items = $db->loadObjectList ();
		
		if ($items) {
			foreach ( $items as $k => $job ) {
				if (isset($job->id)){					
					
				    if( !empty($job->short_desc) )
					   $job->short_desc = JFilterInput::_decode($job->short_desc);
					
					if ($this->_fieldList) {
							foreach ( $this->_fieldList as $field ) {
								
								$job->{$field->field_name} = JFilterInput::_decode ( $job->{$field->field_name} );
									
								if ($field->field_type == 'TEXTFIELD'){
									$job->{$field->field_name} = JFilterInput::clean ( $job->{$field->field_name} );
								}							
	
								
								if ($field->is_referred > 0 && $job->{$field->field_name}) {
									
									
									$values = explode(',', $job->{$field->field_name});
									foreach ($values as $i=>$v){
										$values[$i] = $db->Quote($v);	
									}
									$values = implode(',', $values);
									if(!$values) $values = 0;
									$sql = "SELECT {$field->referred_value} ".
											"\n FROM #__{$field->referred_table} ".
											"\n WHERE {$field->referred_key} in ($values)";
									$db->setQuery ( $sql );
									$result = $db->loadResultArray ();
									if ($result) {
										$job->{$field->field_name} = implode(', ', $result);
									}
									else{
										$job->{$field->field_name} = '';
									}
									
									
								} elseif (in_array ( $field->field_type, array ('RADIO', 'SELECT', 'MSELECT' ) ) && $job->{$field->field_name}) {
									
									$values = explode(',', $job->{$field->field_name});
									foreach ($values as $i=>$v){
										$values[$i] = $db->Quote($v);	
									}
									$values = implode(',', $values);
									$field_id = $field->table_name . '_' . $field->field_name;
									
									$sql = "SELECT text ".
											"\n FROM #__ja_codes ".
											"\n WHERE value in ($values) and field_id='$field_id' ";
																	
									$db->setQuery ( $sql );
									$result = $db->loadResultArray ();
									
									if ($result) {
										$job->{$field->field_name} = implode(', ', $result);
									}
									else{
										$job->{$field->field_name} = '';
									}
								}
						}
						
						$items [$k] = $job;
					}
					
					
				}
			}
		}
		
		return $items;
	
	}
	
	/**
	 * @desc Get all fields that will be displayed on edit form
	 */
	function getEditFieldList($where = '') {
		if (! $this->_fieldListEdit) {
			$this->_fieldListEdit = getEditFieldList ( $this->_table_name );
		}
		return $this->_fieldListEdit;
	}
	
	function getFieldList($where = '') {
		if (! $this->_fieldListEdit) {
			$this->_fieldList = getFieldList ( $this->_table_name, $where );
		}
		
		return $this->_fieldList;
	}
	
	/**
	 * Get field table instance
	 * @return JTable Configuration table object
	 */
	function &_getTable() {
		if ($this->_table == null) {
			$this->_table = &JTable::getInstance ( 'JA_Applications', 'JobBoardTable' );
		}
		
		return $this->_table;
	}
	
	/**
	 * Get page navigator object
	 * @return 
	 */
	function &getPagination() {
		if ($this->_pagination == null) {
			$this->getItems ();
		}
		return $this->_pagination;
	}
	
	/**
	 * Get configuration item
	 * @return JobboardTableJA_resumes Table object
	 */
	function getItem($cid=array()) {		
		$table = & $this->_getTable ();
		// Load the current item if it has been defined
		if(!$cid){
			$cid = JRequest::getVar ( 'cid', array (), '', 'array' );
		}
		JArrayHelper::toInteger ( $cid, array () );
		
		if ($cid) {
			$table->load ( $cid [0] );
		}
		$item = $table;
		return $item;
	}
	
	function getAppItem() {
		
		static $item;
		if (isset ( $item )) {
			return $item;
		}
		$table = & $this->_getTable ();
		$job_id = JRequest::getVar ( 'job_id', 0 );
		$user = &JFactory::getUser ();
		$db = &JFactory::getDBO ();
		if ($job_id && getCurrentUserType () == JBJOB_SEEKER_USER) {
			$query = "SELECT id FROM #__ja_applications WHERE job_id = " . (int)$job_id . " AND user_id = " . (int)$user->id;
			$db->setQuery ( $query );
			$appid = $db->loadResult ();
			$table->load ( $appid );
		}
		
		$item = $table;
		return $item;
	}
	
	function getListItem_Employer($user_id, $limit, $limitstart) {
		if (! $user_id) {
			$user = JFactory::getUser ();
			$user_id = $user->id;
		}
		
		$str_job_list = $this->getListJob_Employer ( $user_id );
		if(JRequest::getVar('job_id', "") != ""){
			$str_job_list = JRequest::getVar('job_id', "");
		}
		if ($str_job_list != '')
			$where_more = " and a.job_id IN (" . $str_job_list . ")";
		else
			$where_more = 'and a.job_id=0';
			
		 if(JRequest::getVar('layout', '') == 'jaempllist'){
			$where_more .= "  and (`params`  NOT LIKE '%employer_removed=1%' or  `params`  IS NULL) ";
		}	
		
		$items = $this->getItems ( $where_more, $limit, $limitstart );
		if (getUserType ( $user_id ) == JBEMPLOYER_USER)
			$this->applicationMailToJobseekerAsRead ( $items );
		return $items;
	
	}
	
	function getListJob_Employer($user_id) {
		if (! $user_id) {
			$user = JFactory::getUser ();
			$user_id = $user->id;
		}
		$db = JFactory::getDBO ();
		$query = "SELECT id FROM #__ja_jobs WHERE user_id=".(int)$user_id;
		
		$db->setQuery ( $query );
		$job_list = $db->loadResultArray ();
		$str_job_list = '';
		if($job_list){
			$str_job_list = implode ( ',', $job_list );
		}
		return $str_job_list;
	}
	
	/** 
	 * Store configuration item
	 * @param array The post array
	 */
	
	function store() {
		global $jbconfig;
		$step = JRequest::getVar ( 'step', '' );
		$db = & JFactory::getDBO ();
		$user = JFactory::getUser ();
		$row = $this->getItem ();
		if ($row->id == null)
			$newapply = 1;
		else
			$newapply = 0;
		$controller = JRequest::getVar ( 'view', 'jaapplications' );
		$post    = JRequest::get('request', JREQUEST_ALLOWRAW);
		$post ['user_id'] = $user->id;
		$opt_attachment = JRequest::getVar ( 'opt_attachment' );
		
		foreach ( $post as $k => $value ) {
			if ($k != 'cid' && is_array ( $value )) {
				$post [$k] = implode ( ',', $value );
			}
			elseif(!is_array ( $value )){
				$post [$k] = trim($value);
			}
		}
		
		if (! $row->bind ( $post )) {
			return false;
		}
		
		if ($row->editor_field)
			$row = assign_editor_field($row);
		
		if ($row->opt_attachment == '1')
			$row->attachment = $this->resume_save_pdf ();
		if ($user->id != null) {
			$row->guest_name = $user->name;
			$row->guest_email = $user->email;
		}
		if ($row->apply_type != '2'){
			if (! $row->check ()) {	
				return false;
			}
		}
		if ($jbconfig['posts']->get('enable_verify_code')) 
		{
			$captcha = JRequest::getVar ( 'security_text', '' );
			if(!$this->validatecaptchaaddnew($captcha)){
				JError::raiseWarning(0,JText::_('Security code is incorrect.'));
				echo JText::_('Security code is incorrect.');
				return false;
			}
		}
		$row->id = 0;		
		if (! $row->store ()) {
			return false;
		} else {
			if ($newapply && $jbconfig ['emails']->get ( 'enabled' )) {
//				if($row->attachment) $row->attachment = JURI::base().$row->attachment;
				if (JRequest::getVar ( 'confirm_email' ))
					$this->applicationMailConfirm ( $row->id, $row->job_id, $row->user_id, 'ApplicationMailConfirm', $row->attachment, $row );
				$this->applicationMailToEmployer ( $row->id, $row->job_id, $row->user_id, 'ApplicationMailToEmployer', $row->attachment, $row );
				return $row->job_id . '_' . JText::_ ( "You have successfully applied for this job" );
			} else
				return $row->job_id . '_' . JText::_ ( "Successfully updated application" );
		}
	
	}
	
	function insertStrToStr($need, $str, $pos) {
		
		$str1 = substr ( $str, 0, $pos );
		$str2 = substr ( $str, $pos );
		$str1 .= $need;
		return $str1 . $str2;
	}
	
	function splitContent($str) {
		$line_length = 160;
		$strlen = strlen ( $str );
		$n = ceil ( $strlen / $line_length );
		$strpos = array ();
		
		$pos = 0;
		$strpos [] = 0;
		do {
			$pos = strpos ( $str, '<br', $pos + 1 );
			if ($pos)
				$strpos [] = $pos;
		
		} while ( $pos > 0 );
		$strpos [] = strlen ( $str );
		$arr_ins = array ();
		for($i = 0; $i < count ( $strpos ); $i ++) {
			
			if ($strpos [$i + 1] - $strpos [$i] > $line_length + 10) {
				for($j = 1; $j < ceil ( ($strpos [$i + 1] - $strpos [$i]) / $line_length ); $j ++) {
					$pos = strpos ( $str, ' ', $line_length * $j + $strpos [$i] );
					if ($pos > $line_length * $j + $strpos [$i] + 10)
						$pos = $line_length * $j + $strpos [$i];
					$arr_ins [] = $pos;
				
				}
			
			}
		
		}
		$str = '<br />' . $str;
		for($i = 0; $i < count ( $arr_ins ); $i ++)
			$str = JobBoardModelJAApplications::insertStrToStr ( '<br />', $str, $arr_ins [$i] + ($i + 1) * 6 );
		
		return $str;
	
	}
	
	function resume_save_pdf() {
		global $jbconfig;
		$user = JFactory::getUser ();
		require_once (JPATH_SITE . DS . 'components' . DS . JBCOMNAME . DS . 'models' . DS . 'jaresumes.php');
		require_once (JPATH_SITE . DS . 'components' . DS . JBCOMNAME . DS . 'asset' . DS . 'rendfield.php');
		$resume_cls = new JobBoardModelJAResumes ( );
		JRequest::setVar ( 'limited', 1 );
		$resume = $resume_cls->getItemView ();
		if (!$resume)
			return '';
		$fieldlist = $resume_cls->getEditFieldList ();
		$user->name = JFilterOutput::stringURLSafe($user->name);
		$filename =  $user->name . "_resume_" . $user->id . ".pdf";
		$data = '';
		$data .= '<div style="border:1px solid;width:100%;">';
		$k = 0;
		for($i = 0, $n = count ( $fieldlist ); $i < $n; $i ++)
			if (! in_array ( $fieldlist [$i]->field_name, array ('id', 'published', 'approved' ) )) {
				$field = $fieldlist [$i];
				$field_name = $field->field_name;
				if (($field->is_hidden))
					continue;
				
				$data .= '<div style="width:100%;">';
				$data .= '<span style="width:30%;float:left;">';
				$data .= $field->label . ": ";
				$data .= '</span>';
				$data .= '<span style="width:70%;float:right;">';
				//						if ($field->field_type!='IMAGE')
				
				if (!$resume->{$field->field_name})
						continue;
				if (($field->field_type == 'FILE')) {
					$file_path = JPATH_SITE.DS.str_replace('/',DS,$resume->{$field->field_name});
					$file_name = explode ( '/', $resume->{$field->field_name} );
					if (file_exists($file_path))
						$data .= '<a href="' . JRoute::_ ( JURI::root () . 'index.php?option=com_jajobboard&view=jaresumes&task=download&cid[]=' . $resume->id ) . '">'.substr ( $file_name [count ( $file_name ) - 1], 14 ).'</a>';
				
				} else
				{
					if (($field->field_type == 'IMAGE')&&$resume->{$field->field_name}) {
						$data .= "<img src='" . $resume->{$field->field_name} . "' alt='photo'  />";
						
						continue;
					}
					$data .= rendfield ( $resume, $field, false, true, true );
				}
				$data .= '</span>';
				$data .= '</span>';
				$data .= '<hr />';
				$data .= '<br />';
				
				$k = 1 - $k;
			}
		$data .= '</div>';
		$document = JDocument::getInstance ( 'pdf' );
		$pdf = $document->_engine;
		$pdf->SetTitle ( $resume->title );
		$pdf->SetSubject ( $resume->title );
		$pdf->SetKeywords ( $document->getMetaData ( 'keywords' ) );
		
		// Set PDF Header data
		$pdf->setHeaderData ( '', 0, 'My Resume', $user->name );
		
		// Set PDF Header and Footer fonts
		$lang = &JFactory::getLanguage ();
		$font = $lang->getPdfFontName ();
		$font = ($font) ? $font : 'freesans';
		$pdf->setRTL ( $lang->isRTL () );
		$pdf->setFont ( 'freesans', '', 7 );
		$pdf->setHeaderFont ( array ($font, '', 10 ) );
		$pdf->setFooterFont ( array ($font, '', 8 ) );
		// Initialize PDF Document
		$pdf->AliasNbPages ();
		$pdf->AddPage ();
		$pdf->writeHTML ( $data, true );
		
		$pdf->Output ( JPATH_SITE . $jbconfig['general']->get('upload_folder',DS.'images'.DS.'stories'.DS.'jbuploads')
.DS.'applications'. DS . date ( 'Ymdhms' ) . $filename, 'F' );
		@chmod(JPATH_SITE . $jbconfig['general']->get('upload_folder',DS.'images'.DS.'stories'.DS.'jbuploads')
.DS.'applications'. DS . date ( 'Ymdhms' ) . $filename, 777);
		
		
		return substr(str_replace(DS,'/', $jbconfig['general']->get('upload_folder',DS.'images'.DS.'stories'.DS.'jbuploads')
),1).'/applications/' . date ( 'Ymdhms' ) . $filename;
	}
	
	function attach_cv() {
		$user = JFactory::getUser ();
		$result = '';
		$resume = getItemByFieldName ( 'ja_resumes', 'user_id', $user->id );
		$resume = $resume [0];
		if ($resume->file_attachment) {
			$source_file = JPATH_ROOT . DS . $resume->file_attachment;
			$dest_file = str_replace ( 'resumes', 'applications', $source_file );
			if (! file_exists ( $dest_file ))
				copy ( $source_file, $dest_file );
			$result = str_replace ( 'resumes', 'applications', $resume->file_attachment );
		}
		return $result;
	}
	
	function increaseViews() {
		$item = $this->getItem ();
		$item->views ++;
		return $this->store ();
	}
	
	/**
	 * Remove field record
	 * @return Number of removed records
	 */
	function remove($task = 'remove') {
		$cid = JRequest::getVar ( 'cid', array (), 'request', 'array' );
		$n = count ( $cid );
		JArrayHelper::toInteger ( $cid );
		$user = &JFactory::getUser ();
		$backend_usertype = array (JBADMIN_USER, JBSUPERADMIN );
		
		if ($user->id && getCurrentUserType () == JBJOB_SEEKER_USER && $n) {
			if ($task == 'remove') {
				$query = "DELETE FROM #__ja_applications WHERE user_id = " . (int)$user->id . " AND id = " . implode ( " OR id = ", $cid );
				
				$db = &JFactory::getDBO ();
				$db->setQuery ( $query );
				if ($db->query ()) {
					return $n;
				}
			}
		} else if ($user->id && getCurrentUserType () == JBEMPLOYER_USER) {
			if ($task == 'remove') {
				$query = "UPDATE  #__ja_applications as a SET a.`job_id` = null WHERE (select count(s.`id`) from #__ja_jobs  as s Where s.`user_id`='{$user->id}' and s.id=a.`job_id`) AND  
																			 `id` = " . implode ( " OR id = ", $cid );
				$db = &JFactory::getDBO ();
				$db->setQuery ( $query );
				if ($db->query ()) {
					return $n;
				}
			}
		} elseif (in_array ( $user->usertype, $backend_usertype ) && $n) {
			if ($task == 'remove') {
				$query = "DELETE FROM #__ja_applications WHERE id = " . implode ( " OR id = ", $cid );
				
				$db = &JFactory::getDBO ();
				$db->setQuery ( $query );
				if ($db->query ()) {
					return $n;
				}
			}
		}
		return 0;
	}
	
	function download() {	    
	    // Check download permission    
	    
		$cid = JRequest::getVar ( 'cid', array (), 'post', 'array' );
		$n = count ( $cid );
		JArrayHelper::toInteger ( $cid );
		
		$item = $this->getItem ();
		$file_name = explode ( '/', $item->attachment );
		if ($item->id && $item->attachment) {
			$file = JPATH_SITE . DS . str_replace ( '/', '\\', $item->attachment );
			if (file_exists ( str_replace ( '/', '\\', $file ) ))
				$file = str_replace ( '/', '\\', $file );
			else
				$file = str_replace ( '\\', '/', $file );
			
			if ( ! file_exists($file) ){
        		echo JText::_("<script language='javascript'> alert('".JText::_("File not found on the Server")."'); </script>");
        		return ;
        	}
        	
            header('Content-Description: File Transfer');
		    header('Content-Type: application/octet-stream');
		    header('Content-Disposition: attachment; filename="'.substr ( $file_name [count ( $file_name ) - 1], 14 ) .'"');
		    header('Content-Transfer-Encoding: binary');
		    header('Expires: 0');
		    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
		    header('Pragma: public');
		    header('Content-Length: ' . filesize($file));
		    ob_clean();
		    flush();
		    readfile($file);
		}
	}
	function applicationMailConfirm($app_id, $job_id, $user_id, $emailTemplate = 'ApplicationMailConfirm', $attachment, $application) {
		$user = JFactory::getUser ( $user_id );
		if ($user->id == 0) {
			$user = new stdClass ( );
			$user->email = JRequest::getVar ( 'guest_email' );
			$user->name = JRequest::getVar ( 'guest_name' );
			$user->id = 0;
		}
		$user_profile = $this->getUserIdFromJobId ( $job_id );
		$profile = getProfileFromUserId ( $user_profile->user_id );
		$resume = getResumeFromUserId ( $user_id );
		if ($resume)
			$resume_id = $resume->id;
		else
			$resume_id = 0;
		$arr_link = array ();
		$arr_link ['users'] = $user_id;
		$arr_link ['ja_profiles'] = $profile->id;
		$arr_link ['ja_resumes'] = $resume_id;
		$arr_link ['ja_jobs'] = $job_id;
		$arr_link ['ja_applications'] = $app_id;
		$mail = get_EmailTemplate ( $arr_link, $emailTemplate, $application->message );
		
		if ($mail) {
			sendMail ( $user->email, $user->name, $mail->subject, $mail->content, '', $mail->EmailFromAddress, $mail->EmailFromName, $attachment );
		}
	}
	
	function applicationMailToEmployer($app_id, $job_id, $user_id, $emailTemplate = 'ApplicationMailToEmployer', $attachment, $application) {
		
		$user_profile = $this->getUserIdFromJobId ( $job_id );
		$user = JFactory::getUser ( $user_profile->user_id );
		$profile = getProfileFromUserId ( $user_profile->user_id );
		$resume = getResumeFromUserId ( $user_id );
		if ($resume)
			$resume_id = $resume->id;
		else
			$resume_id = 0;
		
		$arr_link = array ();
		$arr_link ['users'] = $user_id;
		$arr_link ['ja_profiles'] = $profile->id;
		$arr_link ['ja_resumes'] = $resume_id;
		$arr_link ['ja_jobs'] = $job_id;
		$arr_link ['ja_applications'] = $app_id;
		
		$mail = get_EmailTemplate ( $arr_link, $emailTemplate, $application->message );
		$mail->content = '<img src="' . JURI::root () . 'index.php?option=com_jajobboard&view=jaapplications&tmpl=component&task=sendMailAsRead&cid=' . $app_id . '" />' . $mail->content;
		JRequest::setVar('email_template','ApplicationMailToEmployer');
		sendMail ( $user->email, $user->name, $mail->subject, $mail->content, '', $mail->EmailFromAddress, $mail->EmailFromName, $attachment );
		
	}
	
	function getUserIdFromJobId($job_id) {
		$db = JFactory::getDBO ();
		$query = "SELECT user_id FROM #__ja_jobs WHERE id=".(int)$job_id;
		$db->setQuery ( $query );
		return $db->loadObject ();
	}
	
	function remove_attach() {
		remove_attach ( 'ja_applications' );
	
	}
	function applicationMailToJobseekerAsRead($item_list) {
		if (count($item_list)==0)
			return ;
		$db = JFactory::getDBO ();
		$arr_item_id = array ();
		$arr_user_id = array ();
		
		for($i = 0; $i < count ( $item_list ); $i ++) {
			$arr_item_id [] = $item_list [$i]->id;
			$arr_user_id [] = $item_list [$i]->user_id;
		}
		$query = "SELECT id,user_id FROM #__ja_resumes WHERE user_id IN (" . implode ( ',', $arr_user_id ) . ")";
		$db->setQuery ( $query );
		$arr_resume_id = $db->loadAssocList ();
		$tmp_arr_resume_id = array ();
		for($i = 0; $i < count ( $arr_resume_id ); $i ++) {
			$tmp_arr_resume_id [$arr_resume_id [$i] ['user_id']] = $arr_resume_id [$i] ['id'];
		}
		$arr_resume_id = $tmp_arr_resume_id;
		//Send mail
		$email_template = "mail_to_jobseeker_as_read";
		$arr_link = array ();
		for($i = 0; $i < count ( $arr_user_id ); $i ++)
			if (! $item_list [$i]->read && $item_list [$i]->confirm_email_when_read) {
				JRequest::setVar('guest_name',$item_list[$i]->guest_name);
				$user = JFactory::getUser ( $arr_user_id [$i] );
				if (isset($arr_resume_id [$item_list [$i]->user_id_tmp]))
					$arr_link ['ja_resumes'] = $arr_resume_id [$item_list [$i]->user_id_tmp];
				else 
					$arr_link ['ja_resumes'] = 0;
				$arr_link ['ja_jobs'] = $item_list [$i]->job_id_tmp;
				$arr_link ['ja_applications'] = $item_list [$i]->id;
				$mail = get_EmailTemplate ( $arr_link, $email_template );
				if ($user->id==0)
				{
					$user->email = $item_list[$i]->guest_email;
					$user->name = $item_list[$i]->guest_name;
					
				}
				if ($mail)
					sendMail ( $user->email, $user->name, $mail->subject, $mail->content, '', $mail->EmailFromAddress, $mail->EmailFromName );
			}
			//Mark as read
		$db = JFactory::getDBO ();
		$query = "UPDATE #__ja_applications SET `read`=1 WHERE id IN (" . implode ( ',', $arr_item_id ) . ")";
		$db->setQuery ( $query );
		$result = $db->query ();
	}
	function sendmailAsReadMail() {
		$cid = JRequest::getVar ( 'cid' );
		$resume_id = getItemByFieldName ( 'ja_applications', 'id', $cid );
		$resume_id [0]->user_id_tmp = $resume_id [0]->user_id;
		$resume_id [0]->job_id_tmp = $resume_id [0]->job_id;
		$this->applicationMailToJobseekerAsRead ( $resume_id );
	}
	function validatecaptchaaddnew($arg){
		$captcha = new jacapcha();
		$captcha->text_entered = $arg;
		$captcha->validateText("addnew");
		if($captcha->valid_text){
			return true;
		}else{
			return false;
		}
	}
	function empployer_remove()
	{
		$db = JFactory::getDBO();
		$cids = JRequest::getVar('cid');
		if (!is_array($cids))
			$cids = array($cids);
		
		$user = JFactory::getUser();
		
		foreach ($cids as $cid)
		{			
			$cid = (int)$cid;
			$result = $this->getItem(array($cid));
			$params = new JParameter($result->params);
			
			$where_more = "(select count(s.`id`) from #__ja_jobs  as s Where s.`user_id`='{$user->id}' and s.id=#__ja_applications.job_id )";
			if($result->user_id && !$params->get('jobseeker_removed', 0)){
				$params->def('employer_removed',1);
				$value = $params->toString();
				$query = "UPDATE #__ja_applications SET #__ja_applications.params='$value' WHERE #__ja_applications.id='$cid' and $where_more";
			}
			else{
				$query = "DELETE FROM #__ja_applications WHERE #__ja_applications.id='$cid' and $where_more";
			}
			
			$db->setQuery($query);
			return $db->query();
		}		
		
	}
	function jobseeker_remove()
	{
		$user = JFactory::getUser();
		
		$db = JFactory::getDBO();
		$cids = JRequest::getVar('cid');
		if (!is_array($cids))
			$cids = array($cids);
		foreach ($cids as $cid)
		{			
			$cid = (int)$cid;
			$result = $this->getItem(array($cid));
			$params = new JParameter($result->params);
			if(!$params->get('employer_removed', 0)){
				$params->def('jobseeker_removed',1);
				$value = $params->toString();
				$query = "UPDATE #__ja_applications SET params='$value' WHERE id='$cid' and user_id = " . (int)$user->id ;
			}
			else{
				$query = "DELETE FROM #__ja_applications WHERE id='$cid' and user_id = " . (int)$user->id ;
			}
			$db->setQuery($query);
			return $db->query();
		}
	}

}
?>